package ebhack;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ListIterator;

import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ScriptManager extends ToolModule implements ActionListener, ListSelectionListener {
	private JList fileList;
	private DefaultListModel fileListModel;
	private JButton open, remove;
	
	private ArrayList<String> scripts;
	private String path;
	
	private Project proj;

	public ScriptManager(XMLPreferences prefs) {
		super(prefs);
		
		scripts = new ArrayList<String>();
	}

	public String getDescription() {
		return "Script Manager";
	}

	public String getVersion() {
		return "0.1";
	}

	public String getCredits() {
		return "Written by MrTenda";
	}

	public void init() {
		mainWindow = createBaseWindow(this);
        mainWindow.setTitle(this.getDescription());
        
        fileListModel = new DefaultListModel();
        fileList = new JList(fileListModel);
        fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        fileList.setLayoutOrientation(JList.VERTICAL);
        fileList.setVisibleRowCount(-1);
        fileList.addListSelectionListener(this);
        
        JScrollPane listScroll = new JScrollPane(fileList);
        listScroll.setPreferredSize(new Dimension(200, 80));
        
        JPanel east = new JPanel();
        east.setLayout(new BoxLayout(east, BoxLayout.Y_AXIS));
        
        JButton b = new JButton("New");
        b.setActionCommand("new");
        b.addActionListener(this);
        east.add(b);
        open = new JButton("Open");
        open.setActionCommand("open");
        open.addActionListener(this);
        east.add(open);
        remove = new JButton("Delete");
        remove.setActionCommand("delete");
        remove.addActionListener(this);
        east.add(remove);
        
        mainWindow.getContentPane().add(listScroll, BorderLayout.CENTER);
        mainWindow.getContentPane().add(east, BorderLayout.EAST);
		
        mainWindow.invalidate();
        mainWindow.pack();
        mainWindow.setLocationByPlatform(true);
        mainWindow.validate();
        mainWindow.setResizable(false);
	}
	
	public void show() {
		super.show();
		
		fileListModel.clear();
		ListIterator<String> li = scripts.listIterator();
		while (li.hasNext()) {
			fileListModel.addElement(li.next());
		}
		
		open.setEnabled(false);
		remove.setEnabled(false);
		
		mainWindow.setVisible(true);
	}

	public void load(Project proj) {
		this.proj = proj;
		scripts.clear();
		ListIterator<String> li = proj.getScriptsIterator();
		while (li.hasNext()) {
			scripts.add(li.next());
		}
		
		path = proj.getDirectory();
	}

	public void save(Project proj) { }

	public void hide() {
		if (isInited)
			mainWindow.setVisible(false);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("apply")) {
			proj.setScripts(scripts);
        } else if (e.getActionCommand().equals("close")) {
            hide();
        } else if (e.getActionCommand().equals("new")) {
        	String s = (String)JOptionPane.showInputDialog(
                    mainWindow,
                    "Input the filename for your new script file.",
                    "Input Script Filename",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    null,
                    "");
        	if ((s != null) && (s.length() > 0)) {
        		if (!s.toLowerCase().endsWith(".ccs"))
        			s += ".ccs";
        		File f = new File(path + File.separator + s);
        		if (f.exists()) {
                    JOptionPane.showMessageDialog(mainWindow,
                            "File \"" + s + "\" already exists.",
                            "Could Not Create New File", JOptionPane.ERROR_MESSAGE);
        		} else {
        			try {
						f.createNewFile();
						scripts.add(s);
						fileListModel.addElement(s);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
        		}
        	}
        } else if (e.getActionCommand().equals("open")) {
        	final String textEditor;
        	if (((textEditor = prefs.getValue("textEditor")) == null) || !(new File(textEditor).exists())) {
                JOptionPane.showMessageDialog(mainWindow,
                        "External text editor executable not found.\nPlease select one in the Options menu.",
                        "Could Not Find Executable", JOptionPane.WARNING_MESSAGE);
        	} else {
        		final String file = path + File.separator + scripts.get(fileList.getSelectedIndex());
				SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
				
					public Void doInBackground() {
						try {
							Runtime r = Runtime.getRuntime();
							Process p = r.exec(new String[] { textEditor, file });
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						return null;
					}
				};
				worker.execute();
			}
        } else if (e.getActionCommand().equals("delete")) {
			int ques = JOptionPane.showConfirmDialog(mainWindow,
	                "Are you sure you want to delete this script file?\n"
					+ "It will be permanently deleted.", "Delete?",
	                JOptionPane.YES_NO_OPTION);
	        if (ques == JOptionPane.YES_OPTION) {
	        	new File(path + File.separator + scripts.get(fileList.getSelectedIndex())).delete();
	        	scripts.remove(fileList.getSelectedIndex());
	        	fileListModel.remove(fileList.getSelectedIndex());
	    		open.setEnabled(false);
	    		remove.setEnabled(false);
	        }
        }
	}

	public void valueChanged(ListSelectionEvent e) {
		if (e.getFirstIndex() >= 0) {
			open.setEnabled(true);
			remove.setEnabled(true);
		}
	}

}
